﻿
CREATE PROCEDURE [dbo].[spCloseSeason]
	@SeasonId int = 0,
	@UpdateUser varchar(100)
AS
begin
begin tran	

	declare @UpdateDate Datetime 
	set @UpdateDate = getdate()

	INSERT INTO [dbo].[SeasonPlayerRankings]
           ([SeasonId]
           ,[PlayerId]
           ,[AccountPoints]
           ,[NumberOfMatches]
           ,[InsertUser]
           ,[InsertDate]          
           ,[Deleted])
     select
            @SeasonId
           ,p.Id
           ,p.AccountPoints
           ,isnull(Count(gt.Id), 0)
           ,@UpdateUser
           ,@UpdateDate          
           ,0
	from Players p
		left join GameTeams gt on ((gt.AttackerId = p.Id and gt.Deleted = 0) or (gt.DefenderId = p.Id and gt.Deleted = 0)) 	 
			and gt.SeasonId = @SeasonId
	group by p.Id
           ,p.AccountPoints
		
	select * from [dbo].[SeasonPlayerRankings]	
	order by AccountPoints desc

	--exec('DISABLE TRIGGER trPlayersUpdate ON Players')
		
	update p
	set p.AccountPoints = 100,
		UpdateDate = @UpdateDate,
		UpdateUser = @UpdateUser	
	from Players p		

	--exec('ENABLE TRIGGER trPlayersUpdate ON Players')	

commit tran	
end

